package com.zy.security;

import com.zy.entity.ZyRole;
import com.zy.entity.ZyUser;
import com.zy.mapper.ZyRoleMapper;
import com.zy.mapper.ZyUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 根据当前用户的权限查询用户所拥有的菜单
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    ZyUserMapper zyUserMapper;

    @Autowired
    private ZyRoleMapper zyRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名查找用户
        ZyUser zyUser = zyUserMapper.getUserByUserName(username);

        //未找到该用户
        if (zyUser == null) {
            throw new UsernameNotFoundException("未找到该用户！");
        }

        //用于存放权限信息
        List<GrantedAuthority> list = new ArrayList<>();

        //获取角色信息
        Set<ZyRole> roles = zyRoleMapper.getRoleByUserName(username);

        //存入角色信息
        for (ZyRole role : roles) {
            list.add(new SimpleGrantedAuthority(role.getRoleName()));
        }

        User userdetails = new User(username, zyUser.getPassword(), list);

        return userdetails;
    }

}
